package com.sky.taks;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void processTimeoutOrder(){

        log.info("处理支付超时订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = ordersMapper.getNotPay(Orders.PENDING_PAYMENT,time);
        if(orders!=null && orders.size()>0){
            orders.forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单未支付超时，订单取消");
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            });
        }

    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());
        List<Orders> orders = ordersMapper.getNotPay(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now());
        if(orders!=null && orders.size()>0) {
            orders.forEach(order->{
                order.setStatus(Orders.COMPLETED);
                ordersMapper.update(order);
            });
        }
    }

}